<?php
class SubscribersController extends NewslettersAppController {

	var $name = 'Subscribers';
	var $helpers = array('Html', 'Form', 'Cms.Index');
	var $components = array('Session', 'Cms.GigaMail','Email');
	var $adminOrder = 6;
	var $paginate = array('limit' => 15, 'page' => 1, 'order'=>array('Subscriber.email'=>'asc')); 
	var $uses = array('Newsletters.Subscriber');
	
	function subscribe()
	{
		if($this->getAuthModel('id'))
		{
			$this->data['Subscriber'] = array('entity'=>$this->getAuthModel(),'entity_id'=>$this->getAuthModel('id'));
		}else
		{
			unset($this->data['Subscriber']['entity'],$this->data['Subscriber']['entity_id']);
		}
		if(!empty($this->data))
		{
			unset($this->data['Subscriber']['id']);
			$this->Subscriber->create();
			if($this->Subscriber->save($this->data))
			{
				$msg = 'Thank you for subscribing to our newsleter.';
				if($this->getAuthModel('id') == false)
				{
					if(cr('NewsletterConfig.verify_email') == 1 || is_null(cr('NewsletterConfig.verify_email')))
					{		
						$msg = 'Please click the verification link we just sent to your email address to become a subscriber.';
						$this->__sendMail();		
					}
				}
			
				$this->successMsg(__($msg));
				$this->redirect("/");
			}else
			{
				$this->errorMsg(__('Unable to subscribe!'));
			}
		}
	}

	function admin_index() {
		$this->pageTitle = __("Subscribers");
		$this->Subscriber->recursive = 0;
		$this->paginate['limit'] = 10;
		$this->paginate['conditions'] = array('Subscriber.status'=>Subscriber::ACTIVE);
		$this->paginate['order'] = array('Subscriber.created DESC');
		$this->set('subscribers', $this->paginate());
	}

	function admin_view($id = null)
	{
		$this->pageTitle = __("Subscribers");
		$subscriber = $this->Subscriber->read(null, $id);
		if(empty($subscriber))
	 	{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('subscriber', $subscriber);
	}

	function admin_add() 
	{
		$this->pageTitle = __("Subscribers");
		if($this->data)
		{
			if($this->Subscriber->save($this->data))
			{
				$this->successMsg(__('Entry was saved'));
				$this->redirect(array('action'=>'index'));
			}
		}
	}

	//TO DO: change acc to new configuration 
	function change($code=null, $id=null) {
		$this->Subscriber->recursive = -1;
		$user = $this->Subscriber->findByCode($code);
		if(!$user)
		{
			$this->errorMsg(__('Invalid access'));
			$this->redirect('/');
			return;
		}
		$this->Subscriber->id = $user['Subscriber']['id'];
		if($this->Subscriber->saveField('status',Subscriber::INACTIVE))
		{
			$this->successMsg(__('Your name has been removed from our list'));
		}else
			$this->errorMsg(__('There was some problem please try again'));
		$this->redirect('/');
	}
	
	function activate($code=null)
	{
		$this->Subscriber->recursive = -1;
		$user = $this->Subscriber->findByCode($code);
		if(empty($user))
		{
			$this->errorMsg(__('Invalid access'));
			$this->redirect('/');
			return;
		}
		$this->Subscriber->id = $user['Subscriber']['id'];
		if($this->Subscriber->saveField('status',Subscriber::ACTIVE))
		{
			$this->successMsg(__('Your newsletter service has been activated successfully!'));
		}else
		{
			$this->errorMsg(__('Unable to activated your newsletter service. Please try again'));
		}
		$this->redirect('/');
		exit;
	}
	
	function __sendMail()
	{
		$recipient = Cri('Newsletters.Subscriber')->find('first',array('conditions'=>array('Subscriber.id'=>$this->Subscriber->id)));
		$recipient = $recipient['Subscriber'];
		$this->Email->to = $recipient['email'];
		$this->set(array_keys($recipient),array_values($recipient));
		$this->Email->subject = __('Activate Newsletter Service');
		$this->prepareEmail();		
		$this->Email->return = cr('Newsletter.returnEmail');
		$this->Email->template = 'subscription_activate';
		
		$newsletterActivationUrl = "<a href='".cr('cmsConfig.Backend.siteUrl').'/newsletters/subscribers/activate/'.$recipient['code']."'>".__('activate')." </a>";
		$this->set('newsletterActivationUrl',$newsletterActivationUrl);
					
		$this->Email->send();
		
				
	}
	
	
	function admin_edit($id = null)
	{
		$this->pageTitle = __("Subscribers");
		$subscriber = $this->Subscriber->read(null, $id);
		if(empty($subscriber) && empty($this->data))
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect(array('action'=>'index'));
		}	
		if(!empty($this->data))
		{
			if($this->Subscriber->save($this->data))
			{
				$this->successMsg(__('The Subscriber has been saved.', true));
				$this->redirect(array('action'=>'index'));
			}
		}
		if (empty($this->data))
		{
			$this->data = $subscriber;
		}
	}

	function admin_delete($id = null)
	{
		$this->pageTitle = __("Subscribers");
		$subscriber = $this->Subscriber->read(null, $id);
		if(empty($subscriber))
	 	{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect(array('action'=>'index'));
		}
		if($this->Subscriber->del($id))
		{
			$this->successMsg(__('Subscriber has been deleted.', true));
		}else
		{
			$this->errorMsg(__('Subscriber could not be deleted.', true));
		}
		$this->redirect(array('action'=>'index'));
	}

	function admin_upload() {
		$this->pageTitle = __("Subscribers");
		set_time_limit(0);
		if($this->data)
		{
			if(substr($this->data['Subscriber']['file']['name'], -3, 3)=='csv' || substr($this->data['Subscriber']['file']['name'], -3, 3)=='CSV')
			{
				$row = 1;
				$handle = fopen($this->data['Subscriber']['file']['tmp_name'], "r");
				while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
					$num = count($data);
					$row++;
					if( $data[1]!='')
					{
						$input_subscriber['name'] = $data[0];
						$input_subscriber['email'] = $data[1];
						$this->Subscriber->create();
						$this->Subscriber->save($input_subscriber);
					}
					else
					{
						$error = true;
					}
				}
				fclose($handle);
				$this->successMsg(__("Users uploaded successfully."));
				$this->redirect(array('action'=>'index'));
			}
			else
			{
				$this->errorMsg(__("Please select a CSV file."));
				$this->redirect(array('action'=>'upload'));
			}

			exit;
		}
	}

	function admin_search()
	{
		$this->pageTitle = __("Subscribers");
		$keyword = '';
		$defaultParams['name'] = '';
		$defaultParams['email'] = '';
		$subscribers = array();
		if($this->referer() == '/')
		{
			$this->redirect('/admin/newsletters/subscribers');
		}
		$params = am($defaultParams,$this->data['Subscriber']);
		if(!empty($params['name']))
		{
			$this->paginate['conditions']['OR'][] = array('Subscriber.name LIKE'=>'%'.$params['name'].'%');
			$userModelCondition['AND'][] = array('User.username LIKE'=>'%'.$params['name'].'%');
		}
		if(!empty($params['email']))
		{
			$this->paginate['conditions']['OR'][] = array('Subscriber.email LIKE'=>'%'.$params['email'].'%');
			$userModelCondition['AND'][] = array('User.email LIKE'=>'%'.$params['email'].'%');
				
		}
		
		if(isset($this->params['named']['page']) || isset($this->params['named']['limit']))
		{
			$this->paginate['conditions'] = $this->Session->read('conditions');
			
		}elseif(isset($this->paginate['conditions']))
		{
			$registeredUserIds = $this->Subscriber->find('list',array('fields'=>array('entity_id','entity_id'),'conditions'=>array('not'=>array('entity_id'=>null))));
			if(!empty($registeredUserIds))
			{
				//array('User.username LIKE'=>'%'.$keyword.'%','User.email LIKE'=>'%'.$keyword.'%','User.id'=>$registeredUserIds);
				$userModelCondition['AND'][] = array('User.id'=>$registeredUserIds);
				$entityIdsToSearch = cri('Users.User')->find('list',array('fields'=>array('User.id','User.id'),'conditions'=>$userModelCondition));
				if($entityIdsToSearch)
				{
					$this->paginate['conditions']['OR'][] = array('Subscriber.entity_id'=>$entityIdsToSearch);
				}
			}
			$this->Session->write('conditions',$this->paginate['conditions']);
		}
		if(isset($this->paginate['conditions']))
		{
			$this->Subscriber->recursive = 0;
			$subscribers = $this->paginate();
		}
		$this->pageTitle = __('Search Result');
		$this->set('subscribers', $subscribers);
		$this->render('admin_index');
	}

}
 ?>